package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qianying.comment.CommonResult;
import com.qianying.entity.CustomerContact;
import com.qianying.mapper.CustomerContactMapper;
import com.qianying.service.CustomerContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 客户主要联系人业务逻辑实现
 *
 * @author check
 * @date 2023-10-20
 */
@Service
public class CustomerContactServiceImpl implements CustomerContactService {

    @Autowired
    private CustomerContactMapper customerContactMapper;

    @Override
    public CommonResult<CustomerContact> getById(Long id) {
        // 检查ID是否为空
        if (id == null) {
            return CommonResult.failed("查询失败：ID不能为空");
        }
        CustomerContact entity = customerContactMapper.selectById(id);
        return CommonResult.success(entity);
    }

    @Override
    public CommonResult<CustomerContact> save(CustomerContact entity) {
        // 检查实体是否为空
        if (entity == null) {
            return CommonResult.failed("添加失败：联系人信息不能为空");
        }
        // 添加时强制设置ID为空，确保自增
        entity.setId(null);
        if (entity.getCustomerId() != null) {
            entity.setShopId(null);
        }else if(entity.getCustomerId() == null&&entity.getShopId()==null){
            return CommonResult.failed("添加失败：不能同时设置客户id和门店id为空");
        }

        if (entity.getCustomerId() != null) {
            entity.setShopId(null);
        } else if (entity.getShopId() == null) {
            return CommonResult.failed("添加失败：不能门店客户Id和门店Id同时为空！");
        }
        int count = customerContactMapper.insert(entity);
        return count > 0 ? CommonResult.success(entity, "添加成功") : CommonResult.failed("添加失败");
    }

    @Override
    public CommonResult<?> updateById(CustomerContact entity) {
        // 检查实体是否为空
        if (entity == null) {
            return CommonResult.failed("更新失败：联系人信息不能为空");
        }
        // 检查ID是否存在
        if (entity.getId() == null) {
            return CommonResult.failed("更新失败：ID不能为空");
        }
        int count = customerContactMapper.updateById(entity);
        return count > 0 ? CommonResult.success("更新成功") : CommonResult.failed("更新失败");
    }

    @Override
    public CommonResult<?> removeById(Long id) {
        // 检查ID是否为空
        if (id == null) {
            return CommonResult.failed("删除失败：ID不能为空");
        }
        int count = customerContactMapper.deleteById(id);
        return count > 0 ? CommonResult.success("删除成功") : CommonResult.failed("删除失败");
    }

    @Override
    public CommonResult<List<CustomerContact>> getByCustomerId(Long customerId) {
        // 检查客户ID是否为空
        if (customerId == null) {
            return CommonResult.failed("查询失败：客户ID不能为空");
        }
        List<CustomerContact> list = customerContactMapper.getByCustomerId(customerId);
        return CommonResult.success(list, "获取列表成功");
    }
}